package v1

import (
	"RoccBlog/global"
	"RoccBlog/model"
	"RoccBlog/model/req_resp"
	"RoccBlog/util"
)

type UserRepository struct {
}

func (r *UserRepository) Create(data model.User) error {
	db := global.DB.Begin()
	err := db.Create(&data).Error
	if err != nil {
		db.Rollback()
		return err
	}
	err = db.Model(&data).Association("Roles").Append(data.Roles)
	if err != nil {
		db.Rollback()
		return err
	}

	db.Commit()
	return err
}

func (r *UserRepository) Delete(id int) error {
	db := global.DB.Begin()
	err := db.Model(model.User{Id: id}).Association("Roles").Clear()
	if err != nil {
		db.Rollback()
		return err
	}
	err = db.Delete(&model.User{}, id).Error
	if err != nil {
		db.Rollback()
		return err
	}

	db.Commit()
	return err
}

func (r *UserRepository) Update(data model.User) error {
	return global.DB.Model(&data).Omit("password").Updates(&data).Error
}

func (r *UserRepository) Select(query req_resp.UserQueryReq, pageNum, pageSize int) (any, error) {
	db := global.DB.Model(&model.User{})

	if query.NickName != "" {
		db = db.Where("nick_name like concat('%',?,'%')", query.NickName)
	}

	if query.Email != "" {
		db = db.Where("email like concat('%',?,'%')", query.Email)
	}

	var list []model.User
	var count int64
	var err error
	err = db.Count(&count).Error
	if err != nil {
		return nil, err
	}
	db.Omit("password").Offset(pageSize * (pageNum - 1)).Limit(pageSize).Find(&list)

	return util.ToPageInfo(count, pageSize, pageNum, list), db.Error
}

func (r *UserRepository) SelectById(id int) (model.User, error) {
	var user model.User
	err := global.DB.Preload("Roles").Find(&user, id).Error
	return user, err
}

func (r *UserRepository) SelectByName(username string) (user model.User, err error) {
	err = global.DB.Where("username = ? or email = ?", username, username).Preload("Roles").Find(&user).Error
	return
}

// ResetPassword 重置密码
func (r *UserRepository) ResetPassword(id int, password string) error {
	return global.DB.Model(&model.User{Id: id}).UpdateColumn("password", password).Error
}
